package com.bbzn.user.client.controller;

import com.alibaba.fastjson.JSONObject;
import com.bbzn.user.client.aspect.OperationAnnotation;
import com.bbzn.user.client.constant.*;
import com.bbzn.user.client.dataobject.*;
import com.bbzn.user.client.dto.tenant.TenantClientDTO;
import com.bbzn.user.client.dto.tenant.TenantDTO;
import com.bbzn.user.client.exception.DefinitException;
import com.bbzn.user.client.service.*;
import com.bbzn.user.client.utils.*;
import com.bbzn.user.client.vo.req.TenantVO;
import com.bbzn.user.comment.res.TenantRes;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author wulongbo
 * @Date 2021/3/22 14:30
 * @Version 1.0
 */

@RestController
@RequestMapping("/tenant")
@Slf4j
@Api(value = "Tenant", tags = "租户管理")
public class TenantController extends BaseApiService {
    @Autowired
    private CommonService commonService;

    @Autowired
    private SystemParamByCacheService systemParamByCacheService;

    @Autowired
    private TenantService tenantService;

    @Autowired
    private UserService userService;


    /**
     * 查询租户列表
     *
     * @param reqVO
     * @return
     * @throws Exception
     */
    @OperationAnnotation(content = "查询租户列表")
    @PostMapping(value = "/getTenantList")
    public BaseResponse getTenantList(@RequestBody TenantVO reqVO, HttpServletRequest request) throws Exception {
        String secretKey = commonService.getWebSalt(request);
        if (!OptionalBean.ofNullable(reqVO.getPageSize()).isPresent()) {
            reqVO.setPageSize(PageConstant.PAGE_SIZE);
        }
        if (!OptionalBean.ofNullable(reqVO.getPageNum()).isPresent()) {
            reqVO.setPageNum(PageConstant.PAGE_NUM);
        }
        TenantDTO tenantDTO = new TenantDTO();
        tenantDTO.setPageNum(reqVO.getPageNum());
        tenantDTO.setPageSize(reqVO.getPageSize());
        tenantDTO.setStartIndex((reqVO.getPageNum() - 1) * reqVO.getPageSize());
        if (null != reqVO.getState()) {
            tenantDTO.setState(reqVO.getState());
        }

        PageInfo<Tenant> tenantPageInfo = tenantService.findPageByAll(tenantDTO);
        return setResultSuccess(tenantPageInfo);
    }

    /**
     * 添加用户时选择公司
     *
     * @return
     * @throws Exception
     */
    @OperationAnnotation(content = "添加用户时选择公司")
    @PostMapping(value = "/getUseTenant")
    public BaseResponse getUseTenant(HttpServletRequest request) throws Exception {
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        Tenant tenant = new Tenant();
        tenant.setState(1);
        List<Tenant> tenants = tenantService.findByAll(tenant);
        SystemParam systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.SELECT_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage(), tenants);
    }

    /**
     * 管理员->新增租户
     *
     * @param reqVO
     * @return
     */
    @OperationAnnotation(content = "新增租户")
    @PostMapping(value = "/addTenant")
    public BaseResponse addTenant(@RequestBody TenantVO reqVO, HttpServletRequest request) throws Exception {
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        String userName = MayiktJwtUtils.getUsername(request, secretKey);
        SystemParam systemParam = null;
        if (!OptionalBean.ofNullable(reqVO.getTenantName()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(TenantConstant.TENANT_ENUM, TenantConstant.TENANT_UN_NAME_PREFIX + language);
            return setResultError(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getAddress()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(TenantConstant.TENANT_ENUM, TenantConstant.TENANT_UN_ADDRESS_PREFIX + language);
            return setResultError(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getPhone()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(TenantConstant.TENANT_ENUM, TenantConstant.TENANT_UN_PHONE_PREFIX + language);
            return setResultError(systemParam.getCode(), systemParam.getMassage());
        }
        if (!PhoneFormatCheckUtils.isPhoneLegal(reqVO.getPhone())) {
            systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.PHO_NUM_PREFIX + language);
            return setResultError(systemParam.getCode(), systemParam.getMassage());
        }

        TenantDTO tenantDTO = new TenantDTO();
        tenantDTO.setTenantName(reqVO.getTenantName());
        tenantDTO.setState(1);
        int count = tenantService.findCountByAll(tenantDTO);
        if (count > 0) {
            systemParam = systemParamByCacheService.getValues(TenantConstant.TENANT_ENUM, TenantConstant.TENANT_TENANT_NAME_EXIST_PREFIX + language);
            return setResultError(systemParam.getCode(), systemParam.getMassage());
        }

        reqVO.setState(1);
        reqVO.setCreateTime(new Date());
        reqVO.setCreatedBy(userName);
        tenantService.insert(BabaBeanUtils.voToDto(reqVO, Tenant.class));
        systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.ADD_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());
    }

    /**
     * 修改租户
     *
     * @param reqVO
     * @return
     * @throws Exception
     */
    @OperationAnnotation(content = "修改租户")
    @PostMapping(value = "/updateTenant")
    public BaseResponse updateTenant(@RequestBody TenantVO reqVO, HttpServletRequest request) throws Exception {
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        String userName = MayiktJwtUtils.getUsername(request, secretKey);
        SystemParam systemParam = null;
        if (!OptionalBean.ofNullable(reqVO.getTenantId()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(TenantConstant.TENANT_ENUM, TenantConstant.TENANT_UN_ID_PREFIX + language);
            return setResultError(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getTenantName()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(TenantConstant.TENANT_ENUM, TenantConstant.TENANT_UN_NAME_PREFIX + language);
            return setResultError(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getAddress()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(TenantConstant.TENANT_ENUM, TenantConstant.TENANT_UN_ADDRESS_PREFIX + language);
            return setResultError(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getPhone()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(TenantConstant.TENANT_ENUM, TenantConstant.TENANT_UN_PHONE_PREFIX + language);
            return setResultError(systemParam.getCode(), systemParam.getMassage());
        }
        if (!PhoneFormatCheckUtils.isPhoneLegal(reqVO.getPhone())) {
            systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.PHO_NUM_PREFIX + language);
            return setResultError(systemParam.getCode(), systemParam.getMassage());
        }
        reqVO.setUpdateTime(new Date());
        reqVO.setUpdatedBy(userName);
        tenantService.updateByPrimaryKeySelective(BabaBeanUtils.voToDto(reqVO, Tenant.class));
        systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.MODIFY_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());
    }

    /**
     * 修改租户状态
     *
     * @param reqVO
     * @return
     * @throws Exception
     */
    @OperationAnnotation(content = "修改租户状态")
    @PostMapping(value = "/updateTenantState")
    public BaseResponse updateTenantState(@RequestBody @ApiIgnore TenantVO reqVO, HttpServletRequest request) throws Exception {
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        String userName = MayiktJwtUtils.getUsername(request, secretKey);
        SystemParam systemParam = null;

        if (!OptionalBean.ofNullable(reqVO.getTenantId()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(TenantConstant.TENANT_ENUM, TenantConstant.TENANT_UN_ID_PREFIX + language);
            return setResultError(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getState()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(TenantConstant.TENANT_ENUM, TenantConstant.TENANT_UN_NAME_PREFIX + language);
            return setResultError(systemParam.getCode(), systemParam.getMassage());
        }
        Tenant tenant = BabaBeanUtils.voToDto(reqVO, Tenant.class);
        tenantService.updateByPrimaryKeySelective(tenant);

        Tenant ten = tenantService.selectByPrimaryKey(reqVO.getTenantId());
        //管理员审核通过：
        //1.找到提交申请的人，把该用户升级为公司账号
        if (reqVO.getState() == 1 && null != ten.getUserId()) {
            User user = userService.selectByPrimaryKey(ten.getUserId());
            if (null != user) {
                user.setTenantId(reqVO.getTenantId());
                userService.updateByPrimaryKeySelective(user);
            }
        }

        systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.MODIFY_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());
    }

    /**
     * 删除租户
     *
     * @param reqVO
     * @return
     */
    @OperationAnnotation(content = "删除租户")
    @PostMapping(value = "/delTenant")
    public BaseResponse delTenant(@RequestBody TenantVO reqVO, HttpServletRequest request) throws Exception {
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        Long userId = commonService.getUserId(request);
        SystemParam systemParam = null;
        User user = new User();
        user.setTenantId(reqVO.getTenantId());
        List<User> userList = userService.findByAll(user);
        if (userList.size() > 0) {
            systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.DEL_ERROR_EXIST_SUB_PREFIX + language);
            throw new DefinitException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, systemParam.getMassage());
        }
        tenantService.deleteByPrimaryKey(reqVO.getTenantId());
        systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.DELETE_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());
    }

    /**
     * 查询申请的企业资质
     *
     * @return
     * @throws Exception
     */
    @OperationAnnotation(content = "查询申请的企业资质")
    @PostMapping(value = "/getTenantCompany")
    public BaseResponse getTenantCompany(HttpServletRequest request) throws Exception {
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        Long userId = commonService.getUserId(request);
        String userName = MayiktJwtUtils.getUsername(request, secretKey);
        SystemParam systemParam = null;

//        User user = userService.selectByPrimaryKey(userId);
//        Tenant tenant = tenantService.selectByPrimaryKey(user.getTenantId());

        Tenant tenant = new Tenant();
        tenant.setUserId(userId);
        List<Tenant> tenantList = tenantService.findByAll(tenant);
        JSONObject data = new JSONObject();
        data.put("tenantList", tenantList);
        systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.SELECT_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage(), data);
    }

    /**
     * 升级企业
     *
     * @param reqVO
     * @return
     * @throws Exception
     */
    @OperationAnnotation(content = "升级企业")
    @PostMapping(value = "/upTenantCompany")
    public BaseResponse upTenantCompany(@RequestBody @ApiIgnore TenantVO reqVO, HttpServletRequest request) throws Exception {
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        Long userId = commonService.getUserId(request);
        String userName = MayiktJwtUtils.getUsername(request, secretKey);
        SystemParam systemParam = null;

        User user = userService.selectByPrimaryKey(userId);
        if (null != user.getTenantId()) {
            systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.USER_EXISTS_TENANT_PREFIX + language);
            return setResultError(systemParam.getCode(), systemParam.getMassage());
        }

        if (!OptionalBean.ofNullable(reqVO.getTenantName()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(TenantConstant.TENANT_ENUM, TenantConstant.TENANT_UN_NAME_PREFIX + language);
            return setResultError(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getAddress()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(TenantConstant.TENANT_ENUM, TenantConstant.TENANT_UN_ADDRESS_PREFIX + language);
            return setResultError(systemParam.getCode(), systemParam.getMassage());
        }

        TenantDTO tenantDTO = new TenantDTO();
        tenantDTO.setTenantName(reqVO.getTenantName());
        int count = tenantService.findCountByAll(tenantDTO);
        if (count > 0) {
            systemParam = systemParamByCacheService.getValues(TenantConstant.TENANT_ENUM, TenantConstant.TENANT_TENANT_NAME_EXIST_PREFIX + language);
            return setResultError(systemParam.getCode(), systemParam.getMassage());
        }
        reqVO.setPhone(user.getPhone());
        reqVO.setState(3);  //审核中
        reqVO.setUserId(userId);
        reqVO.setCreateTime(new Date());
        reqVO.setCreatedBy(userName);
        tenantService.insert(BabaBeanUtils.voToDto(reqVO, Tenant.class));
        systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.MODIFY_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());
    }

    @PostMapping("/selectTenantUnUserAll")
    public List<TenantRes> selectTenantUnUserAll() throws Exception {
        return tenantService.selectTenantUnUserAll();
    }

    @PostMapping("/selectTenantUnUser")
    public List<TenantRes> selectTenantUnUser(@RequestBody Long userId) throws Exception {
        List<TenantRes> tenantDTOList = tenantService.selectTenantUnUser(userId);
        User user = userService.selectByPrimaryKey(userId);
        Tenant tenant = tenantService.selectByPrimaryKey(user.getTenantId());
        List<TenantRes> tntDTOList = new ArrayList<>();
        //有公司名称的
        List<TenantRes> haveTnameList = tenantDTOList.stream().filter(t -> (null != t.getTenantName() && !"".equals(t.getTenantName()))).collect(Collectors.toList());
        tntDTOList.addAll(haveTnameList);
        //没有公司名称的
        List<TenantRes> tnameList = tenantDTOList.stream().filter(t -> (null == t.getTenantName() || "".equals(t.getTenantName()))).collect(Collectors.toList());
        ArrayList tnameAList = new ArrayList<Map<String, Object>>();
        List<com.bbzn.user.comment.User> userList = new ArrayList<>();
        tnameList.stream().forEach(ten -> {
            userList.addAll(ten.getUserList());
        });
        Map<String, Object> map = new HashMap<>();//对象的新建应写在循环里面
        map.put("tenantName", tenant.getTenantName());
        map.put("userList", userList);
        tnameAList.add(map);
        tntDTOList.addAll(tnameAList);

        return tntDTOList;
    }

    @PostMapping("/selectByPrimaryKey")
    public com.bbzn.user.comment.Tenant selectByPrimaryKey(@RequestBody Long tenantId) throws Exception {
        Tenant tenant =tenantService.selectByPrimaryKey(tenantId);
        com.bbzn.user.comment.Tenant tet = new com.bbzn.user.comment.Tenant();
        BeanUtils.copyProperties(tet,tenant);
        return tet;
    }

}
